<?php

namespace app\client\services;

use think\facade\Cache;
use think\facade\Validate;

const APPID = 'wx0d4751e5da5616a6';
const SECRET = '3bd5ce266444ba862e81ed893205f009';

class WeChatService extends \app\admin\services\BaseService
{
    /*获取token*/
    protected static function GetAccessToken()
    {
        $token = Cache::get('WxAccessToken');
        if (empty($token->access_token) || ($token->expires_in + $token->addtime < time())) {
            return self::SetAccessToken();
        } else
            return $token->access_token;
    }

    /*设置token*/
    protected static function SetAccessToken()
    {
        $token = json_decode(get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . APPID . '&secret=' . SECRET));
        $token->addtime = time();
        Cache::set('WxAccessToken', $token, 4800);
        return $token->access_token;
    }

    /*微信小程序登录流程*/
    public static function WxLogin($p)
    {
        $rule = [
            'code' => 'require',
        ];
        $validate = Validate::rule($rule);
        if (!$validate->check($p)) {
            api_return(500, $validate->getError());
        }
        if ($_SERVER['HTTP_HOST'] == 'www.yjm.com') {
            $res = [
                'openid' => 'oaJyB4lHATq6Ti7d6fWUsQv-zw_o',
                'session_key' => 'QWERTYUIOP12456'
            ];
        } else {
            $res = json_decode(get('https://api.weixin.qq.com/sns/jscode2session?appid=' . APPID . '&secret=' . SECRET . '&js_code=' . $p['code'] . '&grant_type=authorization_code'),true);
        }
        api_return(200, '', CustomerService::login($res['openid'], 'wx', ($p['avatar']) ?? '', ($p['username']) ?? '用户未授权', $res['session_key']));
    }
}
